import React, { Component } from 'react';
import { Collapse, Form, Col, Row, Modal, Input, Select, DatePicker, Icon, Button } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import styles from '@/pages/Operate.less';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UpkeepInfo from './UpkeepInfo';
import FileImport from '@/components/FileImport';
import router from 'umi/router';
import FileReader from '@/components/FileReader';
import { queryFileList, filterAddFile, filterDeteteFile } from '@/utils/common';
import AntdUpload from '@/components/AntdUpload';
import prompt from '@/components/Prompt';
import AdButton from '@/components/AdButton';
import AntdInput from '@/components/AntdInput';
import { codes, PayMethod } from './utils';
import SearchSelect from '@/components/SearchSelect';
import { columns1 } from '@/pages/Common/common';
const dateFormat = 'YYYY-MM-DD';
const dateFormatByM = 'YYYY-MM';
const { RangePicker, MonthPicker } = DatePicker;
const Panel = Collapse.Panel;
const { TextArea } = Input;
const { Option } = Select;

@connect(({ upkeep, loading, common }) => ({
  upkeep,
  loading: loading.effects['upkeep/upkeepDetail'],
  dictObject: common.dictObject,
}))
@Form.create()
export default class UpkeepOperate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: ['1', '2'],
      fileList: [],
      deleteFileIds: [],
      previewVisible: false,
      previewImage: '',
      ownCompany: '',
      upkeepInfoModalVisible: false,
      visibleFile: false,
      cars: [],
      cars2: [],
      ownCompany2: '',
      disabled: false,
      selectRows: [],
    };
    this.paneSize = ['1', '2'];
    this.fileList = [];
  }

  componentDidMount() {
    const {
      upkeep: { detail },
      match: { params },
      dispatch,
    } = this.props;

    if (params.id) {
      const id = params.id;
      this.queryFileList(id);
      this.setState({ id });
      if (!detail.id) {
        this.getUpkeepDetail(id);
      }
      this.getInfoList(id);
    }

    // 查询字典：保养类型
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'upkeep-type' },
    });
    //币种：
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'currency-type' },
    });
  }
  getInfoList = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'upkeep/upkeepInfoList',
      payload: { id },
    });
  };
  getUpkeepDetail = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'upkeep/upkeepDetail',
      payload: { id },
      callback: data => {
        console.log('data---', data, id);

        if (!data) return;
        this.setState({
          cars: [{ id: data.vehicleId }],
          cars2: [{ id: data.trailerVehicleId }],
        });
        this.setFileList(data.attachments);
      },
    });
  };

  queryFileList = id => {
    queryFileList({
      props: this.props,
      params: { bizId: id, fileBizType: 'UPKEEP_MANA' },
      callback: data => {
        if (!data) return;
        this.fileList = data;
        this.props.form.setFieldsValue({ fileTokens: data });
      },
    });
  };

  setFileList = list => {
    const fileList = list.map(file => {
      const { id, fileUrl } = file;
      return {
        uid: id,
        name: fileUrl.substring(fileUrl.lastIndexOf('\\') + 1, fileUrl.length),
        status: 'done',
        url: `/server/api/tms/tms-attachment/readFile?path=${fileUrl}&token=${localStorage.getItem(
          'token'
        )}`,
        id,
      };
    });
    this.setState({ fileList });
  };

  callback = key => {
    this.setState({
      activeKey: key,
    });
  };
  showDetail = () => {
    this.setState({ upkeepInfoModalVisible: true });
  };
  upkeepInfoHandleCancel = () => {
    this.setState({ upkeepInfoModalVisible: false });
  };

  upkeepInfoHandleOk = () => {
    this.setState({ upkeepInfoModalVisible: true });
  };
  // dispatch 方法
  dispatchFun(type, params) {
    const { dispatch } = this.props;
    dispatch({
      type: type,
      payload: params,
    });
  }

  operatePaneButton = e => {
    e.stopPropagation();
    e.preventDefault();
    const {
      dispatch,
      match: { params },
    } = this.props;
    const { ownCompany, cars, cars2 } = this.state;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { upkeepTime, settlementDate, mdsCompanyId, fileTokens, ...value } = values;
        const { fileList, deleteFileIds } = this.state;
        if (upkeepTime) {
          value.upkeepTime = moment(upkeepTime).format(dateFormat);
        }
        if (settlementDate) {
          value.settlementDate = settlementDate ? moment(settlementDate).format(dateFormatByM) : '';
        }
        value.fileTokens = filterAddFile(fileTokens);
        value.deleteFileIds = filterDeteteFile(fileTokens, this.fileList);
        if (cars.length > 0) {
          const vehicleId = cars.map(v => {
            return v.id;
          });
          value.vehicleId = vehicleId.join(',');
        } else {
          value.vehicleId = '';
        }
        if (cars2.length > 0) {
          value.trailerVehicleId = cars2[0].id;
          console.log('cars[0]', cars2[0].id);
        } else {
          value.trailerVehicleId = '';
        }

        console.log('1234', this.props, params);

        const { id } = this.props;
        if (params.id) {
          value.id = params.id || id;
          dispatch({
            type: 'upkeep/upkeepOperate',
            payload: value,
            callback: () => {
              this.queryFileList(params.id || id);
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
              this.dispatchFun('upkeep/upkeepList', {});
            },
          });
        } else {
          dispatch({
            type: 'upkeep/upkeepOperate',
            payload: value,
            callback: res => {
              this.queryFileList(res);
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
              dispatch({
                type: 'upkeep/upkeepDetail',
                payload: { id: res },
                callback: data => {
                  if (data) {
                    dispatch({
                      type: 'common/setTabsName',
                      payload: {
                        id: res,
                        name: data.upkeepNo,
                        isReplaceTab: true,
                      },
                      callback: result => {
                        if (result) {
                          router.push(`/carDaily/upkeepList/editupkeep/${res}`);
                        }
                      },
                    });
                  }
                },
              });
              this.dispatchFun('upkeep/upkeepList', {});
            },
          });
        }
      }
    });
  };

  // 上传图片
  handleChange = fileList => {
    this.setState({ fileList });
  };

  // 删除图片
  onRemove = deleteFileIds => {
    this.setState({
      deleteFileIds,
    });
  };

  getValue = values => {
    const ownCompany = values.map(v => {
      return v.ownCompanyName;
    });
    this.setState({
      cars: values,
      ownCompany,
    });
  };
  // 挂车车牌号 下拉框事件
  getValueTrailer = values => {
    const ownCompany2 = values.map(v => {
      return v.ownCompanyName;
    });
    this.setState({
      cars2: values,
      ownCompany2,
    });
  };
  handleStandardTableChange = param => {
    const {
      match: { params },
    } = this.props;
    const { formValues } = this.state;
    const values = {
      ...formValues,
      ...param,
    };
    values.id = params.id;
    this.dispatchFun('upkeep/upkeepInfoList', values);
  };

  importFile = e => {
    e.stopPropagation();
    const {
      id,
      match: { params },
    } = this.props;
    if (params.id) {
      this.handleImportFile();
    } else {
      prompt({ content: '请先添加维修保养', type: 'warn' });
    }
  };
  handleImportFile = () => {
    const { visibleFile } = this.state;
    this.setState({ visibleFile: !visibleFile });
  };
  addUpkeepInfo = e => {
    e.stopPropagation();
    const {
      id,
      match: { params },
    } = this.props;
    if (params.id) {
      this.setState({ upkeepInfoModalVisible: true });
    } else {
      prompt({ content: '请先添加维修保养', type: 'warn' });
    }
  };
  onRef = ref => {
    this.child = ref;
  };

  //删除明细
  removeRecord = e => {
    e && e.stopPropagation();
    this.child.removeRecord();
  };

  //勾选明细：
  selected = rows => {
    this.setState({
      selectRows: rows,
    });
  };

  render() {
    const {
      list,
      type,
      form: { getFieldDecorator },
      upkeep: { detail, upkeepInfoList },
      loading,
      dictObject,
      match: { params },
    } = this.props;

    const {
      activeKey,
      previewVisible,
      previewImage,
      fileList,
      ownCompany,
      upkeepInfoModalVisible,
      visibleFile,
      disabled,
      selectRows,
    } = this.state;
    const detailId = params.id;
    const data = upkeepInfoList[detailId] ? upkeepInfoList[detailId] : {};

    const customPanelStyle = {
      borderRadius: 4,
      marginBottom: 12,
      border: 0,
      overflow: 'hidden',
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );
    const panel = detail[detailId];
    const genExtraBasicInfo = () => (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span>{panel ? panel.upkeepNo : '新增维修保养'}</span>
        {disabled ? (
          <AdButton
            type="primary"
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="编辑"
            code={panel ? codes.edit : codes.add}
          />
        ) : (
          <Button.Group>
            <AdButton
              type="primary"
              onClick={e => this.operatePaneButton(e)}
              text="保存"
              code={panel ? codes.edit : codes.add}
            />
            {panel && (
              <AdButton
                onClick={() => {
                  this.setState(preState => ({
                    disabled: !preState.disabled,
                  }));
                }}
                text="取消"
                code={panel ? codes.edit : codes.add}
              />
            )}
          </Button.Group>
        )}
      </div>
    );

    const prefixSelector = type =>
      getFieldDecorator(type == 'payAble' ? 'currencyType' : 'realCurrencyType', {
        initialValue: 'CNY',
      })(
        <Select placeholder="请选择" disabled={disabled}>
          {dictObject['currency-type'] &&
            dictObject['currency-type'].map(item => <Option key={item.code}>{item.value}</Option>)}
        </Select>
      );
    const _gutter = { md: 8, lg: 24, xl: 48 };
    const _col = { md: 12, sm: 24 };
    const _row = { md: 24 };

    return (
      <div className={styles.CollapseUpdate}>
        <FileImport
          visibleFile={visibleFile}
          handleCancel={() => {
            this.handleImportFile();
          }}
          urlImport={`tms/tms-upkeep-detail/importUpkeepDetail?upkeepId=${detailId}`}
          urlCase={`attachment/保养明细导入模板.xlsx`}
          // urlQuery={[
          //   { url: `tms/tms-upkeep-detail/selectList`, payload: { id: detailId } },
          //   { url: `tms/tms-upkeep/viewDetails`, payload: { id: detailId } },
          // ]}
          queryData={[this.getInfoList, this.getUpkeepDetail]}
        />
        <PageHeaderWrapper title={genExtraBasicInfo()}>
          <Collapse activeKey={activeKey} onChange={key => this.callback(key)} bordered={false}>
            {this.paneSize.map((item, panelId) => {
              return (
                <Panel
                  header={`${panelId === 0 ? '基础信息' : '明细'}`}
                  key={`${panelId + 1}`}
                  style={customPanelStyle}
                  extra={
                    panelId === 0 ? null : (
                      <span>
                        <AdButton
                          type="danger"
                          onClick={e => this.removeRecord(e)}
                          ghost
                          text="删除"
                          disabled={selectRows.length > 0 ? false : true}
                          code={codes.removeInfo}
                        />
                        <Button.Group style={{ marginLeft: 8 }}>
                          <AdButton
                            onClick={e => this.importFile(e)}
                            text="导入"
                            disabled={disabled}
                            code={codes.upload}
                          />
                          <AdButton
                            type="primary"
                            onClick={e => this.addUpkeepInfo(e)}
                            text="新增"
                            disabled={disabled}
                            code={codes.addPaper}
                          />
                        </Button.Group>
                      </span>
                    )
                  }
                >
                  {panelId === 0 && (
                    <div className={styles.tableListForm}>
                      <Form layout="inline">
                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="单据号">
                              {getFieldDecorator('upkeepNo', {
                                initialValue: panel ? panel.upkeepNo : '保存后系统自动生成',
                              })(<Input placeholder="请输入单据号" disabled={true} />)}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="车牌号">
                              {getFieldDecorator('vehicleId', {
                                rules: [{ required: true, message: '请选择送保时间' }],
                                initialValue: panel ? panel.vehicleId : undefined,
                              })(
                                <SearchSelect
                                  dataUrl="tms/tms-upkeep/selectVehicle"
                                  url="tms/tms-upkeep/selectVehicleView_s" // selectedData只只有id时需要传url
                                  selectedData={this.state.cars} // 选中值
                                  multiple={false} // 是否多选
                                  showValue="cartPlateOneNo"
                                  searchName="cartPlate"
                                  columns={columns1} // 表格展示列
                                  onChange={this.getValue} // 获取选中值
                                  scrollX={480}
                                  id="upkeep_2"
                                  disabled={disabled}
                                />
                              )}
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="挂车车牌号">
                              {/* rules: [{ required: true, message: '请选择送保时间' }], */}
                              {getFieldDecorator('trailerVehicleId', {
                                initialValue: panel ? panel.vehicleId : undefined,
                              })(
                                <SearchSelect
                                  dataUrl="tms/tms-upkeep/selectVehicle"
                                  url="tms/tms-upkeep/selectVehicleView_s" // selectedData只只有id时需要传url
                                  selectedData={this.state.cars2} // 选中值
                                  multiple={false} // 是否多选
                                  showValue="cartPlateOneNo"
                                  searchName="cartPlate"
                                  columns={columns1} // 表格展示列
                                  onChange={this.getValueTrailer} // 获取选中值
                                  scrollX={480}
                                  id="upkeep_2"
                                  disabled={disabled}
                                />
                              )}
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="所属公司">
                              {getFieldDecorator('mdsCompanyId', {
                                initialValue: ownCompany
                                  ? ownCompany
                                  : panel && panel.ownCompanyName,
                              })(<Input placeholder="请输入" disabled={true} />)}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="类型">
                              {getFieldDecorator('upkeepType', {
                                rules: [{ required: true, message: '请选择' }],
                                initialValue: panel ? panel.upkeepType : undefined,
                              })(
                                <Select placeholder="请选择" disabled={disabled}>
                                  {dictObject['upkeep-type'] &&
                                    dictObject['upkeep-type'].map(item => (
                                      <Option key={item.code}>{item.value}</Option>
                                    ))}
                                </Select>
                              )}
                            </Form.Item>
                          </Col>
                        </Row>

                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="支付方式">
                              {getFieldDecorator('payMethod', {
                                rules: [{ required: true, message: '请选择' }],
                                initialValue: panel ? panel.payMethod : undefined,
                              })(
                                <Select disabled={disabled}>
                                  {PayMethod.map(v => {
                                    return <Option value={v.code}>{v.value}</Option>;
                                  })}
                                </Select>
                              )}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="当前里程">
                              {getFieldDecorator('currentMileage', {
                                // rules: [{ required: true, message: '' }],
                                initialValue: panel ? panel.currentMileage : '',
                              })(<Input placeholder="请输入" disabled={disabled} />)}
                            </Form.Item>
                          </Col>
                        </Row>

                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="应付金额">
                              {getFieldDecorator('totalFee', {
                                initialValue: panel
                                  ? panel.totalFee && Number(panel.totalFee) !== 0
                                    ? Number(panel.totalFee).toFixed(2)
                                    : 0
                                  : '',
                              })(
                                <AntdInput
                                  mode="money"
                                  label="应付金额"
                                  placeholder=""
                                  addonBefore={prefixSelector('payAble')}
                                  disabled={true}
                                />
                              )}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="实付金额">
                              {getFieldDecorator('realPayFee', {
                                initialValue: panel
                                  ? panel.realPayFee && Number(panel.realPayFee) !== 0
                                    ? Number(panel.realPayFee).toFixed(2)
                                    : 0
                                  : '',
                              })(
                                <AntdInput
                                  mode="money"
                                  label="实付金额"
                                  placeholder="长度不超过18位可保留两位小数"
                                  addonBefore={prefixSelector('payActual')}
                                  disabled={disabled}
                                />
                              )}
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="保养厂/维修厂">
                              {getFieldDecorator('upkeepFactory', {
                                rules: [{ required: true, message: '' }],
                                initialValue: panel ? panel.upkeepFactory : '',
                              })(<Input placeholder="请输入" disabled={disabled} />)}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="送保人/送修人">
                              {getFieldDecorator('upkeepPerson', {
                                rules: [{ required: true, message: '' }],
                                initialValue: panel ? panel.upkeepPerson : '',
                              })(<Input placeholder="请输入" disabled={disabled} />)}
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="送保/送修时间">
                              {getFieldDecorator('upkeepTime', {
                                rules: [{ required: true, message: '' }],
                                initialValue:
                                  panel && panel.upkeepTime
                                    ? moment(panel.upkeepTime, dateFormat)
                                    : null,
                              })(<DatePicker disabled={disabled} style={{ width: '100%' }} />)}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="结算周期">
                              {getFieldDecorator('settlementDate', {
                                initialValue:
                                  panel && panel.settlementDate
                                    ? moment(panel.settlementDate, dateFormatByM)
                                    : null,
                              })(<MonthPicker disabled={disabled} style={{ width: '100%' }} />)}
                            </Form.Item>
                          </Col>
                        </Row>

                        <Row gutter={_gutter}>
                          <Col {..._row}>
                            <Form.Item label="备注">
                              {getFieldDecorator('remarks', {
                                initialValue: panel ? panel.remarks : '',
                              })(<TextArea placeholder="请输入" rows={4} disabled={disabled} />)}
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={_gutter}>
                          <Col {..._row}>
                            <Form.Item label="票据">
                              {getFieldDecorator('fileTokens')(
                                <FileReader disabled={disabled} urlType="tms" />
                              )}
                            </Form.Item>
                          </Col>
                        </Row>
                      </Form>
                    </div>
                  )}
                  {panelId === 1 && (
                    <UpkeepInfo
                      id={detailId}
                      data={data}
                      type="list"
                      disabled={disabled}
                      loading={loading}
                      showDetail={this.showDetail}
                      visible={upkeepInfoModalVisible}
                      change={this.handleStandardTableChange}
                      handleCancel={this.upkeepInfoHandleCancel}
                      handleOk={this.upkeepInfoHandleOk}
                      onRef={this.onRef}
                      selected={this.selected}
                    />
                  )}
                </Panel>
              );
            })}
          </Collapse>
        </PageHeaderWrapper>
      </div>
    );
  }
}
